#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Create Date : 1/20/2020
__author__ = 'z417'
import pytest
from webrunner.common.tools import set_env, load_dot_env
from webrunner.common import L


class WebRunner(object):
    """
    Developer Interface: Main Interface
        Usage:
            from webrunner.interface import WebRunner
            runner = WebRunner()
    """

    def __init__(self):
        self.exception_stage = "initialize webrunner()"

    def run(self, path_or_file, report, dot_env, pt=None):
        """
        run test and generate report
        :param path_or_file: test file path or test file name
        :param report: store report in 2 types HTML and XML
        :return:
        """
        try:
            if dot_env:
                env_var, msg = load_dot_env(dot_env)
                if isinstance(env_var, dict):
                    L.info(msg)
                    if env_var:
                        set_env(**env_var)
                elif env_var == 1:
                    L.warn(msg)
        except Exception as e:
            pytest.exit(e, -1)

        xml_name = '{}.xml'.format(report)
        html_name = '{}.html'.format(report)
        args = ['--junitxml={}'.format(xml_name),
                '--html={}'.format(html_name)]
        if pt:
            newA = ['']
            for i in pt.split():
                if i.startswith('-'):
                    newA.append(i)
                else:
                    newA[-1] = '{} {}'.format(newA[-1], i)
            args += newA
        args += list(path_or_file)
        args = [x for x in args if x]
        try:
            pytest.main(args)
            result = 0
        except Exception as e:
            result = 1
            pytest.exit(e, -1)

        return result

    def parse(self, yml_path, pagesP):
        from webrunner.common.tools import gen_page_py
        try:
            gen_page_py(yml_path, pagesP)
            L.info(
                'parse successfull,you can use Xxx.yyy as element object in testcases')
        except Exception as e:
            L.error('parse failed:{}'.format(e))


if __name__ == '__main__':
    WebRunner().parse('po', 'po/pagestest.py')
